#!/bin/bash

scriptPath=$(dirname $0);
echo "generate .trc trace from trace.sqlite (> trace.trc)"

attach="attach 'all-nodes.db' as nodedb;"

if [ -f trace.sqlite ]
then
	query="SELECT round(e.time) as logtime, e.device as nodeA, n.name as nodeB, lower(substr(e.eventName,31,4)) as action  from events as e LEFT JOIN nodedb.table_interfaces as i ON e.interfaceId=i.mac_str LEFT JOIN nodedb.table_nodes as n ON n.rowid=i.node_rowid  WHERE e.eventName='EVENT_TYPE_NEIGHBOR_INTERFACE_UP' OR e.eventName='EVENT_TYPE_NEIGHBOR_INTERFACE_DOWN' ORDER BY nodeA, nodeB, time;"
	sqlite3 -batch -separator ' ' trace.sqlite "$attach $query" | sed 's/\.0//' > tmp-trace
	
	query="SELECT round(min(time)) FROM events WHERE eventName='EVENT_TYPE_NEIGHBOR_INTERFACE_UP' OR eventName='EVENT_TYPE_DATAOBJECT_NEW';"
	startTime=$(sqlite3 -batch -separator ' ' trace.sqlite "$query")

	
	awk -v startTime=$startTime -f $scriptPath/sqlite2trc.awk < tmp-trace | sort -n | sed 's/.* - //' > trace.trc
fi

